# Copyright 2024 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""QwenVL models' APIs."""

import mindspore as ms
import numpy as np
from mindspore import dtype as mstype
from mindspore import nn, Parameter, Tensor
from mindspore import ops
from mindspore.ops import operations as P
from mindformers import PreTrainedModel
from mindformers.modules.layers import LayerNorm
from mindformers.models.clip.clip_modules import Transformer
from llava_config import LlavaConfig


# class VisionTransformer(PreTrainedModel):
#     r"""VisionTransformer Of CLIPModel
#
#     Args:
#         input_resolution (int): The image size of input.
#         patch_size (int): The patch size of vision transformer.
#         width (int): The dimension of vision transformer.
#         layers (int): The number of layers of vision transformer.
#         heads (int): The number of attention heads.
#         output_dim (int): The output dimension of vision transformer.
#         dtype (mstype): The type of calculation, [mstype.float32, mstype.float16].
#     """
#     def __init__(self, config: LlavaConfig):
#         super(VisionTransformer, self).__init__(config.vision_config)
#
#         input_resolution = config.vision_config.image_size
#         patch_size = config.vision_config.patch_size
#         width = config.vision_config.hidden_size
#         layers = config.vision_config.num_hidden_layers
#         heads = config.vision_config.num_attention_heads
#         dtype = config.dtype
#
#         self.conv1 = \
#             nn.Conv2d(
#                 in_channels=3, out_channels=width, kernel_size=patch_size,
#                 stride=patch_size, has_bias=False).to_float(dtype)
#
#         scale = width ** -0.5
#         self.class_embedding = \
#             Parameter(scale * Tensor(np.random.normal(0, 1, size=(width))).astype(ms.float32))
#         self.positional_embedding = \
#             Parameter(scale * Tensor(
#                 np.random.normal(0, 1, size=(
#                     (input_resolution // patch_size) ** 2, width))).astype(ms.float32))
#         self.ln_pre = LayerNorm([width], eps=1e-5)
#         self.transformer = Transformer(width, layers, heads, dtype)
#         self.ln_post = LayerNorm([width], eps=1e-5)
#         self.cat = ops.Concat(1)
#         self.tile = ops.Tile()
#         self.slice = P.StridedSlice()
#         self.dtype = dtype
#         self.load_checkpoint(config.vision_config)
#
#     def construct(self, input_x: ms.Tensor):
#         r"""Construct
#
#         Args:
#             input_x (ms.Tensor): Input tensor.
#
#         Returns:
#             input_x (ms.Tensor): Output tensor.
#         """
#         input_x = self.conv1(input_x)
#         input_x = input_x.reshape(input_x.shape[0], input_x.shape[1], -1)
#         input_x = input_x.transpose(0, 2, 1)
#         input_x = ops.Add()(input_x, self.positional_embedding)
#         input_x = self.ln_pre(input_x)
#         input_x = input_x.transpose(1, 0, 2)
#         input_x = self.transformer(input_x)
#         input_x = input_x.transpose(1, 0, 2)
#         input_x = self.ln_post(input_x)
#         return input_x


class VisionTransformer(PreTrainedModel):
    r"""VisionTransformer Of CLIPModel

    Args:
        input_resolution (int): The image size of input.
        patch_size (int): The patch size of vision transformer.
        width (int): The dimension of vision transformer.
        layers (int): The number of layers of vision transformer.
        heads (int): The number of attention heads.
        output_dim (int): The output dimension of vision transformer.
        dtype (mstype): The type of calculation, [mstype.float32, mstype.float16].
    """
    def __init__(self, config: LlavaConfig = None):
        checkpoint_name_or_path = config.vision_config.checkpoint_name_or_path
        config.vision_config.checkpoint_name_or_path = ""
        super(VisionTransformer, self).__init__(config.vision_config)

        input_resolution = config.vision_config.image_size
        patch_size = config.vision_config.patch_size
        width = config.vision_config.hidden_size
        layers = config.vision_config.num_hidden_layers
        heads = config.vision_config.num_attention_heads
        dtype = config.dtype
        self.conv1 = \
            nn.Conv2d(
                in_channels=3, out_channels=width, kernel_size=patch_size,
                stride=patch_size, has_bias=False).to_float(dtype)

        scale = width ** -0.5
        self.class_embedding = \
            Parameter(scale * Tensor(np.random.normal(0, 1, size=(width))).astype(ms.float32))
        self.positional_embedding = \
            Parameter(scale * Tensor(
                np.random.normal(0, 1, size=(
                    (input_resolution // patch_size) ** 2 + 1, width))).astype(ms.float32))
        self.ln_pre = LayerNorm([width], eps=1e-5)
        self.transformer = Transformer(width, layers, heads, dtype)
        self.ln_post = LayerNorm([width], eps=1e-5)
        self.cat = ops.Concat(1)
        self.tile = ops.Tile()
        self.slice = P.StridedSlice()
        self.dtype = dtype
        config.vision_config.checkpoint_name_or_path = checkpoint_name_or_path
        self.load_checkpoint(config.vision_config)

    def construct(self, input_x: ms.Tensor):
        r"""Construct

        Args:
            input_x (ms.Tensor): Input tensor.

        Returns:
            input_x (ms.Tensor): Output tensor.
        """
        input_x = self.conv1(input_x)
        input_x = input_x.reshape(input_x.shape[0], input_x.shape[1], -1)
        input_x = input_x.transpose(0, 2, 1)
        class_embedding = self.tile(self.class_embedding, (input_x.shape[0]+1, 1, 1)).astype(self.dtype)
        input_x = self.cat([
            self.slice(class_embedding,
                       (0, 0, 0),
                       (-1, class_embedding.shape[1], class_embedding.shape[2]),
                       (1, 1, 1)),
            input_x
        ])
        input_x = ops.Add()(input_x, self.positional_embedding)
        input_x = self.ln_pre(input_x)
        input_x = input_x.transpose(1, 0, 2)
        input_x = self.transformer(input_x)
        input_x = input_x.transpose(1, 0, 2)
        input_x = self.ln_post(input_x[:, 1:, :])
        return input_x
